package com.crazybytex.modbus;


import com.crazybytex.modbus.util.SerialPortParameter;
import com.crazybytex.modbus.util.SerialPortUtil;
import com.serotonin.modbus4j.serial.SerialPortWrapper;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import gnu.io.SerialPort;

/**
 * modbus4j 串口实现
 *
 * @author 程序员潇然 crazybytex.com
 */
public class SerialPortWrapperImpl implements SerialPortWrapper {
    private static final String TAG = SerialPortWrapperImpl.class.getSimpleName();
    /**
     * 串口对象
     */
    private SerialPort serialPort;

    private SerialPortParameter parameter;

    public SerialPortWrapperImpl() {
        super();
    }

    public SerialPortWrapperImpl(SerialPortParameter parameter) {
        this.parameter = parameter;
    }

    @Override
    public void close() throws Exception {
        SerialPortUtil.closeSerialPort(serialPort);
    }

    @Override
    public void open() throws Exception {
        serialPort = SerialPortUtil.openSerialPort(parameter);
    }

    @Override
    public InputStream getInputStream() {
        InputStream in = null;
        try {
            in = serialPort.getInputStream();
        } catch (IOException e) {
            //Log.e(TAG, "获取串口输入流错误", e);
        }

        return in;
    }

    @Override
    public OutputStream getOutputStream() {
        OutputStream out = null;
        try {
            out = serialPort.getOutputStream();
        } catch (IOException e) {
            //  Log.e(TAG, "获取串口输出流错误", e);
        }

        return out;
    }

    @Override
    public int getBaudRate() {
        return parameter.getBaudRate();
    }

    @Override
    public int getDataBits() {
        return parameter.getDataBits();
    }

    @Override
    public int getStopBits() {
        return parameter.getStopBits();
    }

    @Override
    public int getParity() {
        return parameter.getParity();
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("SerialPortWrapperImpl{");
        sb.append("serialPort=").append(serialPort);
        sb.append(", parameter=").append(parameter);
        sb.append('}');
        return sb.toString();
    }
}
